<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>书架 - Saber-Translator</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/variables.css') }}">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/base.css') }}">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/bookshelf.css') }}">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
</head>
<body>
    <!-- 页面头部 -->
    <header class="app-header">
        <div class="header-content">
            <div class="logo-container">
                <a href="/" title="书架首页">
                    <img src="{{ url_for('static', filename='pic/logo.png') }}" alt="Saber-Translator Logo" class="app-logo">
                    <span class="app-name">Saber-Translator</span>
                </a>
            </div>
            <div class="header-links">
                <span class="lan-access-info" id="lanAccessInfo" title="其他设备可通过此地址访问">
                    <span class="lan-icon">🌐局域网设备可通过该网址访问</span>
                    <span id="lanUrl">获取中...</span>
                    <button class="copy-btn" id="copyLanUrl" title="复制地址">📋</button>
                </span>
                <span class="open-source-notice">本项目完全开源免费，请勿上当受骗</span>
                <a href="http://www.mashirosaber.top" target="_blank" class="tutorial-link">使用教程</a>
                <a href="https://github.com/MashiroSaber03/Saber-Translator" target="_blank" class="github-link">
                    <img src="{{ url_for('static', filename='pic/github.jpg') }}" alt="GitHub" class="github-icon">
                </a>
                <button id="themeToggle" class="theme-toggle" title="切换亮暗模式">
                    <span class="theme-icon light-icon">☀️</span>
                    <span class="theme-icon dark-icon">🌙</span>
                </button>
            </div>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="bookshelf-main">
        <!-- 工具栏 -->
        <div class="bookshelf-toolbar">
            <h1 class="page-title">我的书架</h1>
            <div class="toolbar-actions">
                <button id="createBookBtn" class="btn btn-primary">
                    <span class="btn-icon">+</span>
                    <span>新建书籍</span>
                </button>
                <button id="manageTagsBtn" class="btn btn-secondary" onclick="showTagManageModal()">
                    <span>🏷️ 管理标签</span>
                </button>
                <a href="/translate" class="btn btn-secondary">
                    <span>快速翻译</span>
                </a>
            </div>
        </div>

        <!-- 搜索和筛选栏 -->
        <div class="filter-bar">
            <div class="search-box">
                <input type="text" id="searchInput" placeholder="搜索书籍名称或标签..." autocomplete="off">
                <button class="search-btn" onclick="handleSearch()">🔍</button>
                <button class="clear-search-btn" id="clearSearchBtn" onclick="clearSearch()" style="display: none;">✕</button>
            </div>
            <div class="tag-filter" id="tagFilter">
                <span class="filter-label">标签筛选:</span>
                <div class="tag-chips" id="tagChips">
                    <!-- 标签将由JS动态生成 -->
                </div>
            </div>
        </div>

        <!-- 批量操作栏 -->
        <div class="batch-toolbar" id="batchToolbar" style="display: none;">
            <div class="batch-info">
                <input type="checkbox" id="selectAllBooks" onchange="toggleSelectAll()">
                <span id="selectedCount">0</span> 本已选中
            </div>
            <div class="batch-actions">
                <button class="btn btn-sm btn-secondary" onclick="showBatchAddTagModal()">🏷️ 添加标签</button>
                <button class="btn btn-sm btn-secondary" onclick="showBatchRemoveTagModal()">➖ 移除标签</button>
                <button class="btn btn-sm btn-danger" onclick="batchDeleteBooks()">🗑️ 批量删除</button>
                <button class="btn btn-sm btn-secondary" onclick="exitBatchMode()">取消</button>
            </div>
        </div>

        <!-- 书籍网格 -->
        <div class="books-container">
            <div id="booksGrid" class="books-grid">
                <!-- 书籍卡片将由JS动态生成 -->
            </div>
            
            <!-- 空状态提示 -->
            <div id="emptyState" class="empty-state" style="display: none;">
                <div class="empty-icon">📚</div>
                <h2>书架空空如也</h2>
                <p>点击“新建书籍”开始你的翻译之旅</p>
                <button class="btn btn-primary" onclick="showCreateBookModal()">
                    <span class="btn-icon">+</span>
                    <span>新建第一本书</span>
                </button>
            </div>
        </div>
    </main>

    <!-- 新建/编辑书籍模态框 -->
    <div id="bookModal" class="modal">
        <div class="modal-overlay" onclick="closeBookModal()"></div>
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="bookModalTitle">新建书籍</h2>
                <button class="modal-close" onclick="closeBookModal()">&times;</button>
            </div>
            <div class="modal-body">
                <form id="bookForm">
                    <input type="hidden" id="bookId" value="">
                    <div class="form-group">
                        <label for="bookTitle">书籍名称 <span class="required">*</span></label>
                        <input type="text" id="bookTitle" placeholder="请输入书籍名称" required>
                    </div>
                    <div class="form-group">
                        <label>封面图片</label>
                        <div class="cover-upload-area" id="coverUploadArea">
                            <input type="file" id="coverInput" accept="image/*" hidden>
                            <div class="cover-preview" id="coverPreview">
                                <img id="coverPreviewImg" src="" alt="封面预览" style="display: none;">
                                <div class="cover-placeholder" id="coverPlaceholder">
                                    <span class="upload-icon">📷</span>
                                    <span>点击或拖拽上传封面</span>
                                </div>
                            </div>
                        </div>
                        <p class="form-hint">支持 JPG、PNG、WebP 格式，建议比例 3:4</p>
                    </div>
                    <div class="form-group">
                        <label>标签</label>
                        <div class="tag-input-container">
                            <div class="selected-tags" id="bookSelectedTags">
                                <!-- 已选标签将由JS动态生成 -->
                            </div>
                            <div class="tag-dropdown">
                                <input type="text" id="tagInput" placeholder="输入标签名称..." autocomplete="off">
                                <div class="tag-suggestions" id="tagSuggestions" style="display: none;">
                                    <!-- 标签建议将由JS动态生成 -->
                                </div>
                            </div>
                        </div>
                        <p class="form-hint">输入后按回车添加新标签，或从已有标签中选择</p>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeBookModal()">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveBook()">保存</button>
            </div>
        </div>
    </div>

    <!-- 书籍详情/章节列表模态框 -->
    <div id="bookDetailModal" class="modal">
        <div class="modal-overlay" onclick="closeBookDetailModal()"></div>
        <div class="modal-content modal-large">
            <div class="modal-header">
                <h2 id="bookDetailTitle">书籍详情</h2>
                <button class="modal-close" onclick="closeBookDetailModal()">&times;</button>
            </div>
            <div class="modal-body">
                <div class="book-detail-container">
                    <!-- 书籍信息 -->
                    <div class="book-info-section">
                        <div class="book-cover-large" id="detailCover">
                            <img src="" alt="封面" id="detailCoverImg">
                        </div>
                        <div class="book-meta">
                            <h3 id="detailBookTitle">书籍名称</h3>
                            <div class="detail-tags-section">
                                <span class="meta-label">标签：</span>
                                <div class="detail-tags" id="detailBookTags">
                                    <!-- 标签将由JS动态生成 -->
                                </div>
                                <button class="btn-add-tag" onclick="showQuickAddTagModal()" title="添加标签">+</button>
                            </div>
                            <p class="meta-item"><span>章节数：</span><span id="detailChapterCount">0</span></p>
                            <p class="meta-item"><span>创建时间：</span><span id="detailCreatedAt">-</span></p>
                            <p class="meta-item"><span>最后更新：</span><span id="detailUpdatedAt">-</span></p>
                            <div class="book-actions">
                                <button class="btn btn-sm btn-secondary" onclick="editCurrentBook()">编辑书籍</button>
                                <button class="btn btn-sm btn-danger" onclick="deleteCurrentBook()">删除书籍</button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 章节列表 -->
                    <div class="chapters-section">
                        <div class="section-header">
                            <h3>章节列表</h3>
                            <button class="btn btn-sm btn-primary" onclick="showCreateChapterModal()">
                                <span class="btn-icon">+</span> 新建章节
                            </button>
                        </div>
                        <div id="chaptersList" class="chapters-list">
                            <!-- 章节项将由JS动态生成 -->
                        </div>
                        <div id="chaptersEmpty" class="empty-state-small" style="display: none;">
                            <p>暂无章节，点击上方按钮创建</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 新建/编辑章节模态框 -->
    <div id="chapterModal" class="modal">
        <div class="modal-overlay" onclick="closeChapterModal()"></div>
        <div class="modal-content modal-small">
            <div class="modal-header">
                <h2 id="chapterModalTitle">新建章节</h2>
                <button class="modal-close" onclick="closeChapterModal()">&times;</button>
            </div>
            <div class="modal-body">
                <form id="chapterForm">
                    <input type="hidden" id="chapterId" value="">
                    <div class="form-group">
                        <label for="chapterTitle">章节名称 <span class="required">*</span></label>
                        <input type="text" id="chapterTitle" placeholder="例如：第1话、序章" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeChapterModal()">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveChapter()">保存</button>
            </div>
        </div>
    </div>

    <!-- 确认删除模态框 -->
    <div id="confirmModal" class="modal">
        <div class="modal-overlay" onclick="closeConfirmModal()"></div>
        <div class="modal-content modal-small">
            <div class="modal-header">
                <h2>确认删除</h2>
                <button class="modal-close" onclick="closeConfirmModal()">&times;</button>
            </div>
            <div class="modal-body">
                <p id="confirmMessage">确定要删除吗？此操作不可恢复。</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeConfirmModal()">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">删除</button>
            </div>
        </div>
    </div>

    <!-- 标签管理模态框 -->
    <div id="tagManageModal" class="modal">
        <div class="modal-overlay" onclick="closeTagManageModal()"></div>
        <div class="modal-content">
            <div class="modal-header">
                <h2>标签管理</h2>
                <button class="modal-close" onclick="closeTagManageModal()">&times;</button>
            </div>
            <div class="modal-body">
                <div class="tag-manage-form">
                    <div class="form-row">
                        <input type="text" id="newTagName" placeholder="输入新标签名称...">
                        <input type="color" id="newTagColor" value="#667eea" title="选择颜色">
                        <button class="btn btn-primary btn-sm" onclick="createNewTag()">添加</button>
                    </div>
                </div>
                <div class="tag-list" id="tagManageList">
                    <!-- 标签列表将由JS动态生成 -->
                </div>
            </div>
        </div>
    </div>

    <!-- 批量添加标签模态框 -->
    <div id="batchAddTagModal" class="modal">
        <div class="modal-overlay" onclick="closeBatchAddTagModal()"></div>
        <div class="modal-content modal-small">
            <div class="modal-header">
                <h2>批量添加标签</h2>
                <button class="modal-close" onclick="closeBatchAddTagModal()">&times;</button>
            </div>
            <div class="modal-body">
                <p>为 <span id="batchAddTagCount">0</span> 本书籍添加标签:</p>
                <div class="batch-tag-select" id="batchAddTagSelect">
                    <!-- 标签选择将由JS动态生成 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeBatchAddTagModal()">取消</button>
                <button type="button" class="btn btn-primary" onclick="confirmBatchAddTags()">确认添加</button>
            </div>
        </div>
    </div>

    <!-- 批量移除标签模态框 -->
    <div id="batchRemoveTagModal" class="modal">
        <div class="modal-overlay" onclick="closeBatchRemoveTagModal()"></div>
        <div class="modal-content modal-small">
            <div class="modal-header">
                <h2>批量移除标签</h2>
                <button class="modal-close" onclick="closeBatchRemoveTagModal()">&times;</button>
            </div>
            <div class="modal-body">
                <p>从 <span id="batchRemoveTagCount">0</span> 本书籍移除标签:</p>
                <div class="batch-tag-select" id="batchRemoveTagSelect">
                    <!-- 标签选择将由JS动态生成 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeBatchRemoveTagModal()">取消</button>
                <button type="button" class="btn btn-danger" onclick="confirmBatchRemoveTags()">确认移除</button>
            </div>
        </div>
    </div>

    <!-- 快速添加标签模态框 -->
    <div id="quickAddTagModal" class="modal">
        <div class="modal-overlay" onclick="closeQuickAddTagModal()"></div>
        <div class="modal-content modal-small">
            <div class="modal-header">
                <h2>为书籍添加标签</h2>
                <button class="modal-close" onclick="closeQuickAddTagModal()">&times;</button>
            </div>
            <div class="modal-body">
                <div class="quick-tag-input">
                    <input type="text" id="quickTagInput" placeholder="输入标签名称或选择已有标签..." autocomplete="off">
                </div>
                <div class="quick-tag-list" id="quickTagList">
                    <!-- 可选标签将由JS动态生成 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeQuickAddTagModal()">关闭</button>
            </div>
        </div>
    </div>

    <!-- Toast 通知 -->
    <div id="toast" class="toast"></div>

    <script src="{{ url_for('static', filename='js/bookshelf.js') }}"></script>
    <script>
        // 主题切换
        const themeToggle = document.getElementById('themeToggle');
        const savedTheme = localStorage.getItem('theme') || 'light';
        document.body.setAttribute('data-theme', savedTheme);
        
        themeToggle.addEventListener('click', () => {
            const currentTheme = document.body.getAttribute('data-theme');
            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
            document.body.setAttribute('data-theme', newTheme);
            localStorage.setItem('theme', newTheme);
        });

        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            loadBooks();
            loadTags();
            loadServerInfo();
            
            // 搜索框回车事件
            document.getElementById('searchInput').addEventListener('keypress', (e) => {
                if (e.key === 'Enter') handleSearch();
            });
            
            // 搜索框实时搜索（防抖）
            let searchTimeout;
            document.getElementById('searchInput').addEventListener('input', (e) => {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(() => handleSearch(), 300);
                // 显示/隐藏清除按钮
                document.getElementById('clearSearchBtn').style.display = e.target.value ? 'flex' : 'none';
            });
            
            // 标签输入框事件
            const tagInput = document.getElementById('tagInput');
            if (tagInput) {
                tagInput.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        addTagToBook(tagInput.value.trim());
                    }
                });
                tagInput.addEventListener('focus', () => showTagSuggestions());
                tagInput.addEventListener('input', () => showTagSuggestions());
            }
            
            // 点击外部关闭标签建议
            document.addEventListener('click', (e) => {
                if (!e.target.closest('.tag-dropdown')) {
                    document.getElementById('tagSuggestions').style.display = 'none';
                }
            });
        });

        // 获取服务器信息（局域网地址）
        async function loadServerInfo() {
            try {
                const response = await fetch('/api/server-info');
                const data = await response.json();
                if (data.success) {
                    const lanUrlEl = document.getElementById('lanUrl');
                    lanUrlEl.textContent = data.lan_url;
                    lanUrlEl.setAttribute('data-url', data.lan_url);
                    
                    // 复制按钮功能
                    document.getElementById('copyLanUrl').addEventListener('click', async (e) => {
                        e.preventDefault();
                        const url = data.lan_url;
                        try {
                            await navigator.clipboard.writeText(url);
                            showToast('局域网地址已复制！');
                        } catch (err) {
                            // Fallback for older browsers
                            const textArea = document.createElement('textarea');
                            textArea.value = url;
                            document.body.appendChild(textArea);
                            textArea.select();
                            document.execCommand('copy');
                            document.body.removeChild(textArea);
                            showToast('局域网地址已复制！');
                        }
                    });
                }
            } catch (error) {
                console.error('获取服务器信息失败:', error);
                document.getElementById('lanUrl').textContent = '获取失败';
            }
        }
    </script>
</body>
</html>

